package opt_slice

import (
	"fmt"
	"github.com/google/uuid"
	"math/rand"
	"reflect"
	sync2 "sync"
	"time"
)

func Slice_cap() {
	var slice = []int{1, 3, 4, 5, 6, 7, 8, 9, 10, 11}
	fmt.Println("slice len: ", len(slice), "slice cap:", cap(slice))

	s1 := slice[1:2:5]
	fmt.Println(s1)
	fmt.Println("slice len: ", len(s1), "slice cap:", cap(s1))

	s1[0] = 100
	fmt.Println(s1)

	fmt.Println(slice)
}

func About_slice_cap() {
	slice := make([]int, 0)

	for i := 0; i < 2048; i++ {
		slice = append(slice, i)
		fmt.Println(cap(slice))
	}
}

func About_map() {
	var opt_map = map[float64]interface{}{}
	var opt_map_1 = map[float64]interface{}{}
	opt_map[100] = "2345"
	opt_map_1[100] = "2345"
	for i := 0; i < 100; i++ {
		opt_map[float64(i)] = uuid.New()
		delete(opt_map, float64(i/2))

	}
	fmt.Println("opt_map len ", len(opt_map))
	fmt.Println(reflect.DeepEqual(opt_map, opt_map_1))
}

func Work_timer() {
	tick := time.Tick(1 * time.Second)

	for {
		select {
		case <-tick:
			fmt.Println("延迟执行")
		}
	}
}

var wg sync2.WaitGroup

func Defer_multiple_chain() {
	rand.NewSource(time.Now().UnixNano())
	data_ch := make(chan int, 1000)
	stop_ch := make(chan struct{})

	for i := 0; i < 1000; i++ {
		go func() {
			for {
				select {
				case <-stop_ch:
					return
				case data_ch <- rand.Intn(1000):
				}
			}
		}()

	}
	wg.Add(1)
	go func() {
		defer wg.Done()
		for ch := range data_ch {
			if ch == 999 {
				fmt.Println("===== send stop signal to senders")
				stop_ch <- struct{}{}
			}
			fmt.Println("=====", ch)
		}
	}()

	wg.Wait()

}

func slice_opt() {
	var s []string
	// print true, true
	fmt.Println("uninit :", s, s == nil, len(s) == 0)

	s = make([]string, 3)
	fmt.Println("emp", s, "len:", len(s), "cap:", cap(s))

	s[0] = "a"
	s[1] = "b"
	s[2] = "c"
	fmt.Println("set:", s)
	fmt.Println("get:", s[2])

	fmt.Println("len:", len(s))

	s = append(s, "d")
	s = append(s, "e", "f")
	fmt.Println("apd:", s, "cap:", cap(s))

	// deep clone
	c := make([]string, len(s))
	copy(c, s)

	fmt.Printf("Address of c:%p  c type %T \n", &c, &c)
	fmt.Printf("Address of s:%p  s type %T \n", &s, &s)

	c[1] = "23"

	fmt.Println("copy :c", c, "source ", s)

}

func map_opt() {
	m := make(map[string]int)
	m["kty"] = 4
	m["kty2"] = 10

	fmt.Println("map:", m)

	delete(m, "nil")

	clear(m)
	fmt.Println(m)
}
